package com.jiayinlending.function.home.fragment;

import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.jiayinlending.CommonConstant;
import com.jiayinlending.R;
import com.jiayinlending.base.BaseFragment;
import com.jiayinlending.model.Sms;
import com.jiayinlending.model.ToSignSms;
import com.jiayinlending.util.MD5Util;
import com.jiayinlending.util.StringUtils;
import com.jiayinlending.util.TLog;
import com.jiayinlending.util.sign.SignHelper;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by yuexiaohui on 2017/5/6 11:46
 */

public class RegisterFragment extends BaseFragment {

    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_smsCode)
    EditText etSmsCode;
    @BindView(R.id.tv_get_resCode)
    TextView tvGetResCode;
    @BindView(R.id.bt_next)
    Button btNext;
    private long time = new Date().getTime();


    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_register;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        etPhone.addTextChangedListener(mTextWatcher);
        etSmsCode.addTextChangedListener(mTextWatcher);
    }

    @OnClick({R.id.tv_get_resCode, R.id.bt_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_get_resCode:
                if (getPhoneNumStates()) {
                    sendVerificationCode();
                    getSms();
                } else {
                    Toast.makeText(curActivity, "请输入手机号码", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.bt_next:
                if (getPhoneNumStates() && etSmsCode.getText().toString().length() == 6 && !TextUtils.isEmpty(etSmsCode.getText().toString())) {
                    
                } else {
                    Toast.makeText(curActivity, "请输重新获取验证码", Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }

    @Override
    protected void onAfterTextChanged(Editable s) {
        super.onAfterTextChanged(s);
        if (getPhoneNumStates()) {
            tvGetResCode.setEnabled(true);
            tvGetResCode.setClickable(true);
        } else {
            tvGetResCode.setEnabled(false);
            tvGetResCode.setClickable(false);
        }
    }

    private boolean getPhoneNumStates() {
        String phoneNum = etPhone.getText().toString();
        if (TextUtils.isEmpty(phoneNum)) {
            return false;
        } else if (phoneNum.length() > 11 || phoneNum.length() < 11) {
            return false;
        } else if (!StringUtils.matchCellNum(phoneNum)) {
            return false;
        }
        return true;
    }

    public static final String SMS_TYPE_REG = "reg";

    private String getSgn(String phone) {
        ToSignSms toSignSms = new ToSignSms(phone, SMS_TYPE_REG, String.valueOf(time));
        String content = SignHelper.sortParamForSignCard(toSignSms);
        String sgn = "";
        sgn = MD5Util.getInstance().sign(content, CommonConstant.MD5_KEY);
        return sgn;
    }

    private void getSms() {
        String phone = etPhone.getText().toString();
        Observable<Sms> sms = sHomeApi.getSms(phone, SMS_TYPE_REG, String.valueOf(time), getSgn(phone))
                .observeOn(AndroidSchedulers.mainThread());
        sms.subscribe(new Observer<Sms>() {
            @Override
            public void onCompleted() {
                Toast.makeText(curActivity, "验证码发送成功", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(Sms sms) {
                System.out.println("验证码onNext");

            }
        });

    }

    private void sendVerificationCode() {
        final int count = 60;
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(count + 1)
                .map(new Func1<Long, Long>() {
                    @Override
                    public Long call(Long aLong) {
                        return count - aLong;
                    }
                })
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        tvGetResCode.setEnabled(false);
                        tvGetResCode.setBackgroundResource(R.drawable.btn_pressed);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onCompleted() {
                        TLog.error("发送验证码", "" + "onCompleted");
                        tvGetResCode.setText("获取验证码");
                        tvGetResCode.setBackgroundResource(R.drawable.btn_normal);
                        tvGetResCode.setTextColor(Color.WHITE);
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(Long aLong) {
                        TLog.error("发送验证码", "" + "onNext: " + aLong);
                        tvGetResCode.setText(aLong + "s");
                        tvGetResCode.setEnabled(true);
                        tvGetResCode.setTextColor(Color.WHITE);
                    }
                });
    }

}
